import express, { Request, Response, Router } from 'express';
import { PrismaClient } from '@prisma/client';
import { ResponseHelper } from '../utils/response';
import { authenticateToken, requireAdmin } from '../middleware/auth';

const router: Router = express.Router();
const prisma = new PrismaClient();

/**
 * 获取推荐菜品列表（分页）
 * GET /api/v1/dishes
 * 查询参数：
 * - page: 页码（默认1）
 * - limit: 每页数量（默认20）
 * - locationId: 地点ID筛选（可选）
 */
router.get('/', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 20;
    const locationId = req.query.locationId ? parseInt(req.query.locationId as string) : undefined;
    const skip = (page - 1) * limit;

    // 构建查询条件
    const where: any = {};
    if (locationId && !isNaN(locationId)) {
      where.locationId = locationId;
    }

    // 并行查询数据和总数
    const [dishes, total] = await Promise.all([
      prisma.recommendedDish.findMany({
        where,
        select: {
          id: true,
          locationId: true,
          userId: true,
          dishName: true,
          floor: true,
          price: true,
          imageUrl: true,
          createdAt: true,
          location: {
            select: {
              id: true,
              name: true,
              status: true
            }
          },
          user: {
            select: {
              id: true,
              nickname: true,
              avatarUrl: true
            }
          }
        },
        skip,
        take: limit,
        orderBy: {
          createdAt: 'desc'
        }
      }),
      prisma.recommendedDish.count({ where })
    ]);

    ResponseHelper.paginated(
      res,
      dishes,
      {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit)
      },
      '推荐菜品列表获取成功'
    );
  } catch (error) {
    console.error('获取推荐菜品列表失败:', error);
    ResponseHelper.serverError(res, '获取推荐菜品列表失败', error);
  }
});

/**
 * 获取推荐菜品详情
 * GET /api/v1/dishes/:id
 */
router.get('/:id', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const id = parseInt(req.params.id);

    if (isNaN(id)) {
      ResponseHelper.validationError(res, [{ field: 'id', message: '无效的菜品ID' }]);
      return;
    }

    const dish = await prisma.recommendedDish.findUnique({
      where: { id },
      select: {
        id: true,
        locationId: true,
        userId: true,
        dishName: true,
        floor: true,
        price: true,
        imageUrl: true,
        createdAt: true,
        location: {
          select: {
            id: true,
            name: true,
            coordinateX: true,
            coordinateY: true,
            status: true
          }
        },
        user: {
          select: {
            id: true,
            nickname: true,
            avatarUrl: true,
            username: true
          }
        }
      }
    });

    if (!dish) {
      ResponseHelper.notFound(res, '推荐菜品不存在');
      return;
    }

    ResponseHelper.success(res, dish, '推荐菜品详情获取成功');
  } catch (error) {
    console.error('获取推荐菜品详情失败:', error);
    ResponseHelper.serverError(res, '获取推荐菜品详情失败', error);
  }
});

/**
 * 删除推荐菜品
 * DELETE /api/v1/dishes/:id
 */
router.delete('/:id', authenticateToken, requireAdmin, async (req: Request, res: Response) => {
  try {
    const id = parseInt(req.params.id);

    if (isNaN(id)) {
      ResponseHelper.validationError(res, [{ field: 'id', message: '无效的菜品ID' }]);
      return;
    }

    // 检查菜品是否存在
    const dish = await prisma.recommendedDish.findUnique({
      where: { id },
      select: { id: true, locationId: true }
    });

    if (!dish) {
      ResponseHelper.notFound(res, '推荐菜品不存在');
      return;
    }

    // 删除菜品
    await prisma.recommendedDish.delete({
      where: { id }
    });

    ResponseHelper.success(res, null, '推荐菜品删除成功');
  } catch (error) {
    console.error('删除推荐菜品失败:', error);
    ResponseHelper.serverError(res, '删除推荐菜品失败', error);
  }
});

export default router;
